<?php

namespace App\Http\Controllers;

use App\Http\Services\SMSServices;
use App\Models\Person;
use App\Models\Sendlog;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class LoginController extends Controller
{
    public function login(Request $request): JsonResponse
    {
        $username = $request->input('username');
        $password = $request->input('password');
        $user = User::query()
            ->where('username', $username)
            ->first();

        if (!$user || !Hash::check($password, $user->password)) {
            return $this->error('用户名或密码错误');
        }
        Log::info('登录成功', ['user' => $user->id]);
        return $this->success([
            'access_token' => $user->createToken('user')->plainTextToken,
        ]);
    }

    public function userInfo(Request $request): JsonResponse
    {
        $user = Auth::user();
        if (!$user) {
            return $this->error('请重新登录！', 403);
        }
        $data = [
            'name' => $user->name,
            'roles' => ['admin'],
        ];
        return $this->success($data);
    }

    /**
     * 发送单独的短信
     * @param
     * @return
     * @author ScorpionFong
     */
    public function sendMsg(Request $request): JsonResponse
    {
        $phone = $request->input('phone');
        if (!$phone) {
            return $this->error('请输入手机号');
        }
        if (Sendlog::where('phone', $phone)->where('created_at', '>=', date('Y-m-d 00:00:00'))->count() > 10) {
            return $this->error('今日发送次数已达上限');
        }
        $code = rand(1000, 9999);
        $data = [
            'phone' => $phone,
            'content' => $code,
            'status' => 0,
            'is_used' => 0
        ];
        Sendlog::create($data);
        SMSServices::sendSMS($phone, json_encode(['code' => $code]));
        return $this->success();
    }

    public function logout(): JsonResponse
    {
        $user = Auth::user();
        $user->tokens()->delete();
        return $this->success();
    }

    public function changePwd(Request $request): JsonResponse
    {
        try {
            $this->validate($request, [
                'old_pwd' => 'required',
                'new_pwd' => 'required',
                'new_pwd2' => 'required|same:new_pwd',
            ], [
                'old_pwd.required' => '请输入旧密码',
                'new_pwd.required' => '请输入新密码',
                'new_pwd2.required' => '请输入确认密码',
                'new_pwd2.same' => '两次密码不一致',
            ]);
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        }
        $user = Auth::user();
        if (!Hash::check($request->input('old_pwd'), $user->password)) {
            return $this->error('旧密码错误');
        }
        $user->password = Hash::make($request->input('new_pwd'));
        $user->save();
        return $this->success();
    }

    /**
     * 移动端手机号验证码登录
     * @param
     * @return
     * @author ScorpionFong
     */
    public function mobileLogin(Request $request): JsonResponse
    {
        try {
            $this->validate($request, [
                'phone' => 'required',
                'code' => 'required',
            ], [
                'phone.required' => '请输入手机号',
                'code.required' => '请输入验证码',
            ]);
        } catch (ValidationException $e) {
            return $this->error($e->validator->errors()->first());
        }
        $code = Sendlog::where('phone', $request->input('phone'))->where('content', $request->input('code'))->where('is_used', 0)->where('created_at', '>=', date('Y-m-d H:i:s', time() - 600))->orderByDesc('id')->first();
        if (!$code) {
            return $this->error('验证码已过期或输入错误');
        }
        $person_id = 0;
        $person = Person::query()->where('phone', $request->input('phone'))->first();
        if (!$person) {
            $res = Person::create(['phone' => $request->input('phone')]);
            $person_id = $res->id;
        } else {
            $person_id = $person->id;
        }
        // Sendlog::where('id', $code->id)->update(['is_used' => 1]);
        return $this->success(['person_id' => $person_id]);
    }
}
